#pragma once


#include<iostream>
#include<stdio.h>
#include<string>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<netinet/in.h>

class udpClient
{
  private:
    std::string ip;
    int port;
    int sock;
  public:
    udpClient(std::string _ip="127.0.0.1",int _port = 8080)
      :ip(_ip)
      ,port(_port)
    {}
   void initClient()
   {
     sock = socket(AF_INET,SOCK_DGRAM,0);
     std::cout<<"socket:"<<sock<<std::endl;
   }
   void start()
   {
         
     std::string msg;
     struct sockaddr_in peer;
     peer.sin_family = AF_INET;
     peer.sin_port = htons(port);
     peer.sin_addr.s_addr = inet_addr(ip.c_str());
    for(;;)
    {
      std::cout<<"please enter:";
      std::cin>> msg;
      if(msg == "quit")
      {
        break;    
      }

   sendto(sock,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,sizeof(peer));
         
   char echo[128];
   ssize_t s = recvfrom(sock,echo,sizeof(echo)-1,0,nullptr,nullptr);
           if(s > 0)
           {
               echo[s] = 0;
               std::cout<<"Server:"<<echo<<std::endl;
           }
  }
   }    
   ~udpClient()
   {
     close(sock);
   } 
};
